<?php if (!defined('BASEPATH'))exit('No direct script access allowed');
/**
 * 登录、注册、找回密码控制器
 */
class Site extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('new_task_model');
        $this->load->model('experience_list_model');
        $this->load->model('finance_list_model');
        $this->load->model('finance_list_model');
        $this->load->model('users_spread_model');
    }
    //登录
    function login() {
        if($this->userinfo){
            redirect("");
        }
        if($_POST){
            $loginName = isset($_POST['uName']) ? trim($_POST['uName']) : "" ;
            $loginPass = isset($_POST['uPass']) ? trim($_POST['uPass']) : "" ;
            $redirectUrl = isset($_POST['redirectUrl']) ? trim($_POST['redirectUrl']) : site_url("") ;
            //检测用户名
            if(!$loginName){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '登录用户名不能为空';
                echo JSON($mess);exit;
            }
            if(!$loginPass){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '登录密码不能为空';
                echo JSON($mess);exit;
            }
            $uinfo = "";
            if(check_email($loginName)){
                $uinfo = $this->users_model->get_user_by_email($loginName);
            }elseif(check_mobile($loginName)){
                $uinfo = $this->users_model->get_user_by_mobile($loginName);
            }else{
                $uinfo = $this->users_model->get_user_by_username($loginName);
            }
            if(!$uinfo){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '登录用户名输入有误';
                echo JSON($mess);exit;
            }
            
            //查看是否被锁定
            if($uinfo['status'] == 0){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '您的账户处于锁定状态，禁止登录';
                echo JSON($mess);exit;
            }
            $ip = $this->input->ip_address();
            $is_pass = $uinfo['password'] == md5(md5($loginPass) . $uinfo['salt']);
            //验证密码
            if(!$is_pass){
                $mess['errorMsg'] = '登录密码错误';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            //登录成功，写入日志记录
            $log_data = array();
            $log_data['user_id'] = $uinfo['user_id'];
            $log_data['events'] = 'login';
            $log_data['content'] = '微信登录成功';
            $log_data['ip'] = $ip;
            $log_data['create_time'] = time();
            $this->users_model->insert_log($log_data);
            
            //写入登录日志
            $login_log_data = array();
            $login_log_data['user_id'] = $uinfo['user_id'];
            $login_log_data['login_flag'] = 2;
            $login_log_data['login_ip'] = $ip;
            $login_log_data['create_time'] = time();
            $login_log_data['month'] = date("Ym");
            $login_log_data['day'] = date("Ymd");
            $this->users_model->insert_login_log($login_log_data);
            
            
            //更改用户信息
            $data = array();
            $data['login_times'] = $uinfo['login_times'] + 1;
            $data['last_ip'] = $uinfo['login_ip'];
            $data['last_time'] = $uinfo['login_time'];
            $data['login_ip'] = $ip;
            $data['login_time'] = time();
            $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
            $this->users_model->user_update($data,$uinfo['user_id']);
            
            //登录
            $info = array();
            $info['uuid'] = encrypt_user_id($uinfo['user_id']);
            $info['user_id'] = $uinfo['user_id'];
            $info['uname'] = $uinfo['username'];
            $info['mobile_flag'] = $uinfo['mobile'] ? 1 : 0;
            $info['email_flag'] = $uinfo['email'] ? 1 : 0;
            $info['last_ip'] = $data['last_ip'];
            $info['last_time'] = $data['last_time'];
            $this->session->set_userdata('userinfo', $info);
            
            $mess['reqStatus'] = true;
            $mess['url'] = $redirectUrl;
            echo JSON($mess);exit;
            
        }
        if($this->userinfo){
            redirect("index");
        }
        $redirectUrl = isset($_GET['redirectUrl']) ? $_GET['redirectUrl'] : "";
        $this->assign("redirectUrl", $redirectUrl);
        $this->display('site/login.html');
    }
    //注册
    function reg() {
        if($this->userinfo){
            redirect("");
        }
        if($_POST){
            //获取新手任务配置
            $this->new_task = $this->config_task['new_task'];
            $umobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";//注册手机号
            $password = isset($_POST['uPass']) ? trim($_POST['uPass']) : "";//密码
            $checkCode = isset($_POST['uCode']) ? trim($_POST['uCode']) : "" ;//验证注册验证码
            $redirectUrl = isset($_POST['redirectUrl']) ? trim($_POST['redirectUrl']) : site_url("");

            $ip = $this->input->ip_address();
            //验证手机号是否为空
            if(!$umobile){
                $mess['errorMsg'] = "手机号不能为空";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证手机号格式
            if(!preg_match("/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-3,5-9]{1})|(17[0,1,3,5-8]{1})|(18[0-9]{1}))+\d{8})$/",$umobile)){
                $mess['errorMsg'] = '手机号格式不正确';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证码用户名的唯一性
            if($this->users_model->get_user_flag(array("mobile"=>$umobile,"is_line"=>0))){
                $mess['errorMsg'] = '手机号已经被注册';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证密码
            if(!$password){
                $mess['errorMsg'] = '密码不能为空';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机验证码不能为空';
                echo JSON($mess);exit;
            }
            if($checkCode != $this->session->userdata('register_code')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '验证码输入有误';
                echo JSON($mess);exit;
            }
            if($umobile != $this->session->userdata('register_mobile')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机和验证码不匹配';
                echo JSON($mess);exit;
            }
            if ($this->request_plat){
                $request_plat = $this->request_plat;
            }else{
                $request_plat = 0;
            }
            
            $parent_id = $this->session->userdata('parent_id') ? $this->session->userdata('parent_id') : 0;
            //判断是否有效用户
            if($parent_id && $parent_id != "" && $parent_id != 0){
                $parent_user = $this->users_model->get_user_by_uid($parent_id);
                if($parent_user && $parent_user['status'] == 0){
                    $mess['errorMsg'] = '注册失败';
                    $mess['errorCode'] = 1000;
                    $mess['reqStatus'] = false;
                    echo JSON($mess);exit;
                }
            }
            
            /*******************/
            //判断是否线下注册,如果是，则删除
            $line_user = $this->users_model->get_user(array("mobile"=>$umobile,"is_line"=>1));
            if($line_user){
                $user_id = $line_user['user_id'];
                $this->db->where(array('mobile'=>$umobile))->update("tan_users_line",array('is_reg'=>1));
            }
            /***********************/
            //生成salt
            $salt = random_string('alnum', 6);
            //生成加密密码
            $md5pass = md5(md5($password) . $salt);
            //写入数据库
            $data = array();
            $data['username'] = "tll".$umobile;
            $data['password'] = $md5pass;
            $data['parent_id'] = $parent_id;
            $data['mobile'] = $umobile;
            $data['email'] = '';
            $data['salt'] = $salt;
            $data['mobile_isApprove'] = 1;
            $data['reg_ip'] = $this->input->ip_address();
            $data['reg_time'] = time();
            $data['reg_flag'] = 2;//注册来源(1、PC，2、微信，3、Android，4、ios)
            $data['reg_plat'] = $request_plat;//注册平台来源
            $data['login_times'] = 1;
            $data['login_ip'] = $this->input->ip_address();
            $data['login_time'] = time();
            $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
            $data['last_ip'] = $this->input->ip_address();
            $data['last_time'] = time();
            if($user_id){
                $data['is_line'] = 0;
                $this->db->where("user_id",$user_id)->update("tan_users",$data);
            }else{
                //创建用户注册信息
                $user_id = $this->users_model->insert($data);
            }
            $month = date('Ym');
            $day = date('Ymd');
            if($user_id){
                $task_first_finance = $this->new_task[0]['award_finance'];//首次任务注册奖励
                $task_first_experience = $this->new_task[0]['award_experience'];//首次任务注册奖励
                
                $task_second_finance = $this->new_task[1]['award_finance'];//首次绑定手机奖励
                $task_second_experience = $this->new_task[1]['award_experience'];//首次绑定手机奖励
                
                //推荐人信息
                if($parent_id){
                    $spread_data = array('user_id'=>$user_id,'parent_id'=>$parent_id,'create_time'=>  time(),'month'=>$month,'day'=>$day);
                    $this->users_spread_model->insert($spread_data);
                    //插入推广记录
                }
                //用户附加信息
                $img_index = rand(0, 9);
                $info_data = array();
                $info_data['user_id'] = $user_id;
                $info_data['truename'] = "";
                $info_data['idcard'] = "";
                $info_data['head_img'] = "http://static.tan66.com/upfiles/head/s/".  $img_index.".jpg";
                $info_data['head_small_img'] = "http://static.tan66.com/upfiles/head/m/".  $img_index.".jpg";
                $info_data['nickname'] = "tan66-".encrypt_user_id($user_id);
                $info_data['create_time'] = time();
                if($line_user){//下线用户更新
                    $this->db->where("user_id",$user_id)->update("tan_users_info",$info_data);
                }else{
                    $this->users_model->insert_user_info($info_data);//插入用户附加信息
                }
                //用户账户信息
                $account_data = array();
                $account_data['user_id'] = $user_id;
                $account_data['total'] = $task_first_finance + $task_second_finance;//账户总额
                $account_data['balance'] = $task_first_finance + $task_second_finance;//可用余额
//                $account_data['experience'] = $task_first_experience + $task_second_experience;//当前积分
//                $account_data['experience_balance'] = $task_first_experience + $task_second_experience;//可用积分
                $this->account_model->insert($account_data);//插入用户账号信息
                
                //新手任务
                $new_user_task1 = array();
                $new_user_task1['user_id'] = $user_id;
                $new_user_task1['step'] = 1;
                $new_user_task1['reward_worth'] = $this->new_task[0]['award_finance'];
                $new_user_task1['reward_experience'] = $this->new_task[0]['award_experience'];
                $new_user_task1['is_finish'] = 1;
                $new_user_task1['is_receive'] = 1;
                $new_user_task1['receive_time'] = time();
                $new_user_task1['finish_time'] = time();
                $new_user_task1['create_time'] = time();
                $this->new_task_model->insert($new_user_task1);//新手任务第一步
                
                $new_user_task2 = array();
                $new_user_task2['user_id'] = $user_id;
                $new_user_task2['step'] = 2;
                $new_user_task2['reward_worth'] = $this->new_task[1]['award_finance'];
                $new_user_task2['reward_experience'] = $this->new_task[1]['award_experience'];
                $new_user_task2['is_finish'] = 1;
                $new_user_task2['is_receive'] = 1;
                $new_user_task2['receive_time'] = time();
                $new_user_task2['finish_time'] = time();
                $new_user_task2['create_time'] = time();
                $this->new_task_model->insert($new_user_task2);//新手任务第二步
                
                $new_user_task3 = array();
                $new_user_task3['user_id'] = $user_id;
                $new_user_task3['step'] = 3;
                $new_user_task3['reward_worth'] = $this->new_task[2]['award_finance'];
                $new_user_task3['reward_experience'] = $this->new_task[2]['award_experience'];
                $new_user_task3['is_finish'] = 0;
                $new_user_task3['is_receive'] = 0;
                $new_user_task3['receive_time'] = 0;
                $new_user_task3['finish_time'] = 0;
                $new_user_task3['create_time'] = time();
                $this->new_task_model->insert($new_user_task3);//新手任务第三步
                
                //奖励通知
                $message = "恭喜您完成新手任务第一步【".$this->new_task[0]['title']."】,奖励您".$this->new_task[0]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[0]['award_experience']."积分
                $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time())); 
                
                //奖励通知
                $message = "恭喜您完成新手任务第二步【".$this->new_task[1]['title']."】,奖励您".$this->new_task[1]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[1]['award_experience']."积分
                $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time()+10)); 
                $current_time = time();
                
                if(1){
                   //资金明细
                    $finance_data = array();
                    $finance_data['user_id'] = $user_id;
                    $finance_data['content'] = '新人注册奖励礼包'.$task_first_finance.'溜溜币';
                    $finance_data['finance'] = $task_first_finance;
                    $finance_data['finance_balance'] = $account_data['balance'] - $task_second_finance;
                    $finance_data['reward_type'] = 'task_award';
                    $finance_data['type'] = 1;
                    $finance_data['create_time'] = $current_time;
                    $finance_data['month'] = $month;
                    $finance_data['day'] = $day;
                    $this->finance_list_model->insert($finance_data); 
                    
                    $finance_data = array();
                    $finance_data['user_id'] = $user_id;
                    $finance_data['content'] = '首次绑定手机奖励'.$task_second_finance.'溜溜币';
                    $finance_data['finance'] = $task_second_finance;
                    $finance_data['finance_balance'] = $account_data['balance'];
                    $finance_data['reward_type'] = 'task_award';
                    $finance_data['type'] = 1;
                    $finance_data['create_time'] = $current_time + 10;
                    $finance_data['month'] = $month;
                    $finance_data['day'] = $day;
                    $this->finance_list_model->insert($finance_data);
                }
                
                /*********社区相关start********/
                //创建社区用户表
                $this->bbs_user_model->insert_bbs_user(array("user_id"=>$user_id,"salt"=>$salt,"reg_time"=>  time(),"group_id"=>1,"create_time"=>  time()));
                //创建社区用户账户表
                $this->bbs_user_model->insert_bbs_account(array("user_id"=>$user_id));
                //创建社区个人统计表
                $this->bbs_user_model->insert_bbs_count(array("user_id"=>$user_id));
                
                //添加个人动态
                //$this->insert_behavior(array('user_id'=>$this->userinfo['user_id'],"operator_id"=>0,"event_type"=>"event_reg"));
                //系统通知
                $this->insert_notice(array('user_id'=>0,"operator_id"=>0,"recieve_id"=>$user_id,"event_type"=>"event_reg","type"=>"system","content"=>"欢迎来到弹溜溜社区大家庭！！"));
                /*********社区相关end********/
                //发送欢迎私信
                $this->send_dialog($user_id,$salt);
                
                //用户日志
                $log_data = array();
                $log_data['user_id'] = $user_id;
                $log_data['events'] = 'register';
                $log_data['content'] = '注册成功';
                $log_data['ip'] = $this->input->ip_address();;
                $log_data['create_time'] = time();
                $this->users_model->insert_log($log_data);
                
                //写入登录日志
                $login_log_data = array();
                $login_log_data['user_id'] = $user_id;
                $login_log_data['login_flag'] = 2;
                $login_log_data['login_ip'] = $ip;
                $login_log_data['create_time'] = time();
                $login_log_data['month'] = date("Ym");
                $login_log_data['day'] = date("Ymd");
                $this->users_model->insert_login_log($login_log_data);
                
                //登录
                $info = array();
                $info['uuid'] = encrypt_user_id($user_id);
                $info['uname'] = "tll".$umobile;
                $info['mobile_flag'] = 1;
                $info['email_flag'] = 0;
                $info['last_ip'] = $data['last_ip'];
                $info['last_time'] = $data['last_time'];
                $this->session->set_userdata('userinfo', $info);
                
                $this->session->set_userdata("register_code","");
                $this->session->set_userdata("register_mobile","");
                
                $mess['reqStatus'] = true;
                $mess['url'] = $redirectUrl?$redirectUrl:($this->redirectLink ? $this->redirectLink : site_url(""));
                echo JSON($mess);exit;
            }
            
        }
        if($this->userinfo){
            redirect("index");
        }
        $redirectUrl = isset($_GET['redirectUrl']) ? $_GET['redirectUrl'] : "";
        $this->assign("redirectUrl", $redirectUrl);
        $this->display('site/reg.html');
    }
    //找回密码
    function findpwd() {
        if($_POST){
            $umobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";//找回密码手机号
            $checkCode = isset($_POST['uCode']) ? trim($_POST['uCode']) : "" ;//验证注册验证码
            //验证手机号是否为空
            if(!$umobile){
                $mess['errorMsg'] = "手机号不能为空";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证手机号格式
            if(!preg_match("/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-3,5-9]{1})|(17[0,1,3,5-8]{1})|(18[0-9]{1}))+\d{8})$/",$umobile)){
                $mess['errorMsg'] = '手机号格式不正确';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证码用户名的唯一性
            if(!$this->users_model->get_user_flag(array("mobile"=>$umobile,"is_line"=>0))){
                $mess['errorMsg'] = '手机号不存在';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机验证码不能为空';
                echo JSON($mess);exit;
            }
            if($checkCode != $this->session->userdata('findpwd_code')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '验证码输入有误或已失效';
                echo JSON($mess);exit;
            }
            if($umobile != $this->session->userdata('findpwd_mobile')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机和验证码不匹配';
                echo JSON($mess);exit;
            }
            $this->session->set_userdata("findpwd_code","");
            $this->session->set_userdata("findpwd_mobile","");
            $this->session->set_userdata("u_mobile",$umobile);
            
            $mess['reqStatus'] = true;
            $mess['url'] = site_url("account/resetpwd");
            echo JSON($mess);exit;
        }
        if($this->userinfo){
            redirect("");
        }
        $this->session->set_userdata("findpwd_code","");
        $this->session->set_userdata("findpwd_mobile","");
        $this->display('site/findpwd.html');
    }
    //重置密码
    function resetpwd() {
        if($_POST){
            $umobile = $this->session->userdata('u_mobile');
            $newPass = isset($_POST['newPass']) ? trim($_POST['newPass']) : "";
            if(!$newPass){
                $mess['errorMsg'] = "新密码验证失败";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            $uinfo = $this->users_model->get_user(array("mobile"=>$umobile,"is_line"=>0));
            if(!$uinfo){
                $mess['errorMsg'] = "身份校验失败";
                $mess['errorCode'] = 1000;
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            $newLoginPass = md5(md5($newPass) . $uinfo['salt']);
            $data = array("password"=>$newLoginPass);
            $result = $this->users_model->user_update($data,  $uinfo['user_id']);
            if($result){
                $this->session->set_userdata("u_mobile","");
                $mess['reqStatus'] = true;
                $mess['url'] = site_url("account/login");
                echo JSON($mess);exit;
            }else{
                $mess['errorMsg'] = "操作失败,请稍后重试";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
        }
        if($this->userinfo){
            redirect("");
        }
        if(!$this->session->userdata('u_mobile')){
            redirect("account/findpwd");
        }
        $this->display('site/resetpwd.html');
    }
    
    //绑定手机验证手机号
    function checkmobile(){
        $this->is_login();
        if($_POST){
            if(!$this->userinfo){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "请先登录，再操作哦";
                echo JSON($mess);exit;
            }
            $checkCode = isset($_POST['uCode']) ? trim($_POST['uCode']) : "" ;//验证验证码
            $umobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";//验证手机号
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机验证码不能为空';
                echo JSON($mess);exit;
            }
            if($checkCode != $this->session->userdata('checkmobile_code')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '验证码输入有误或已失效';
                echo JSON($mess);exit;
            }
            if($umobile != $this->session->userdata('checkmobile_mobile')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机和验证码不匹配';
                echo JSON($mess);exit;
            }
            $this->session->set_userdata("checkmobile_code","");
            $this->session->set_userdata("checkmobile_mobile","");
            
            $mess['reqStatus'] = true;
            $mess['url'] = site_url("account/bindmobile");
            echo JSON($mess);exit;
        }
        $this->session->set_userdata("checkmobile_code","");
        $this->session->set_userdata("checkmobile_mobile","");
        $mobile = $this->db->query("select mobile from tan_users where user_id = ".$this->user_id." order by user_id desc limit 1")->row_array();
        $this->assign("mobile_s",  mobile_formart($mobile['mobile']));
        $this->assign("mobile",  $mobile['mobile']);
        $this->display('site/checkmobile.html');
    }
    //新手机号绑定
    function bind_mobile(){
        if($_POST){
            if(!$this->userinfo){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "请先登录，再操作哦";
                echo JSON($mess);exit;
            }
            $checkCode = isset($_POST['uCode']) ? trim($_POST['uCode']) : "" ;//验证验证码
            $umobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";//绑定手机号
            
            if(!$umobile){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机号不能为空';
                echo JSON($mess);exit;
            }
            $flag = $this->users_model->get_user_flag(array("mobile"=>$umobile,"is_line"=>0));
            if($flag){
                $mess['errorMsg'] = '手机号已被注册';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            } 
            
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机验证码不能为空';
                echo JSON($mess);exit;
            }
            if($checkCode != $this->session->userdata('bindmobile_code')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '验证码输入有误或已失效';
                echo JSON($mess);exit;
            }
            if($umobile != $this->session->userdata('bindmobile_mobile')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机和验证码不匹配';
                echo JSON($mess);exit;
            }
            
            
            //获取用户信息
            $user = $this->users_model->get_user_by_uid($this->user_id);
            $data = array();
            $data['mobile'] = $umobile;
            $user['mobile_isApprove'] == 0 ? $data['mobile_isApprove'] = 1 : "";
            $result = $this->users_model->user_update($data,  $this->user_id);
            if($result){
                if($user['mobile_isApprove'] == 0 ){
                    
                    
                    /*******************/
                    //判断是否线下注册,如果是，则删除
                    $line_user = $this->users_model->get_user(array("mobile"=>$umobile,"is_line"=>1));
                    if($line_user){
                        $this->db->where(array('user_id'=>$line_user['user_id']))->delete("tan_usres");
                        $this->db->where(array('user_id'=>$line_user['user_id']))->delete("tan_usres_info");
                        $this->db->where(array('mobile'=>$umobile))->update("tan_users_line",array('is_reg'=>1));
                        //转移投资记录
                        $this->db->where(array('user_id'=>$line_user['user_id']))->update("tan_plat_invest_list",array("user_id"=>$this->userinfo['user_id']));
                    }
                    /***********************/
                    
                    
                    $this->new_task = $this->config_task['new_task'];
                    $finance_award = $this->new_task[1]['award_finance'];
                    //获取账号信息
                    $account = $this->account_model->get($this->user_id);
                    //更新账号信息
                    $account_data = array();
                    $account_data['total'] = $account['total'] + $finance_award;
                    $account_data['balance'] = $account['balance'] + $finance_award;
                    $this->account_model->update($account_data,$this->user_id);
                    //奖励溜溜币
                    $finance_data = array();
                    $finance_data['user_id'] = $this->user_id;
                    $finance_data['content'] = "首次绑定手机奖励".$finance_award."溜溜币";
                    $finance_data['finance'] = $finance_award;
                    $finance_data['finance_balance'] = $account_data['balance'];
                    $finance_data['reward_type'] = 'task_award';
                    $finance_data['type'] = 1;
                    $finance_data['create_time'] = time();
                    $finance_data['month'] = date("Ym");
                    $finance_data['day'] = date("Ymd");
                    $this->finance_list_model->insert($finance_data);
                    
                    $new_task_step = array();
                    $new_task_step['is_finish'] = 1;
                    $new_task_step['is_receive'] = 1;
                    $new_task_step['finish_time'] = time();
                    $new_task_step['receive_time'] = time();
                    $this->new_task_model->update($new_task_step,array('user_id'=>$this->user_id,'step'=>2));
                    
                    //奖励通知
                    $message = '恭喜您完成新手任务第二步【'.$this->new_task[1]['title'].'】，奖励您'.$finance_award."溜溜币。感谢您对弹溜溜的支持！";
                    $this->db->insert("users_award_notice", array('user_id'=>$this->user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time()));
                    
                    //写入日志记录
                    $log_data = array();
                    $log_data['user_id'] = $this->user_id;
                    $log_data['events'] = 'newbindphone';
                    $log_data['content'] = '手机首绑成功';
                    $log_data['ip'] = $this->input->ip_address();
                    $log_data['create_time'] = time();
                    $this->users_model->insert_log($log_data);
                }
                
                $this->session->set_userdata("bindmobile_code","");
                $this->session->set_userdata("bindmobile_code","");
                
                $mess['reqStatus'] = true;
                $mess['url'] = site_url("account/security");
                echo JSON($mess);exit;
                
            }else{
                $mess['errorMsg'] = "操作失败，请稍后重试";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
        }
    }
    /**
     * 第三方绑定注册
     */
    function third_bind(){
        if($_POST){
            $umobile = isset($_POST['uMobile']) ? trim($_POST['uMobile']) : "";//绑定手机号
            $upass = isset($_POST['upass']) ? trim($_POST['upass']) : "tll123456";//初始化注册密码
            $checkCode = isset($_POST['uCode']) ? trim($_POST['uCode']) : "" ;//验证注册验证码
            $qc_info = isset($_POST['uQcinfo']) ? json_decode(base64_decode(trim($_POST['uQcinfo'])),true) : "" ;//第三方账户信息
            $utype = isset($_POST['uType']) ? trim($_POST['uType']) : "" ;//第三方类型
            //验证手机号是否为空
            if(!$umobile){
                $mess['errorMsg'] = "手机号不能为空";
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            //验证手机号格式
            if(!preg_match("/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-3,5-9]{1})|(17[0,1,3,5-8]{1})|(18[0-9]{1}))+\d{8})$/",$umobile)){
                $mess['errorMsg'] = '手机号格式不正确';
                $mess['reqStatus'] = false;
                echo JSON($mess);exit;
            }
            
            if(!$checkCode){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机验证码不能为空';
                echo JSON($mess);exit;
            }
            if($checkCode != $this->session->userdata('thirdlogin_code')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '验证码输入有误或已失效';
                echo JSON($mess);exit;
            }
            if($umobile != $this->session->userdata('thirdlogin_mobile')){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = '手机和验证码不匹配';
                echo JSON($mess);exit;
            }
            $this->session->set_userdata("thirdlogin_code","");
            $this->session->set_userdata("thirdlogin_mobile","");
            
            //验证码用户名
            $uinfo = $this->users_model->get_user(array('mobile'=>$umobile,"is_line"=>0));
            $user_id = $uinfo["user_id"];
            if($uinfo){//老用户绑定
                if($utype == "qq"){//qq
                    $this->users_model->del_qq_bind($uinfo['user_id']);
                    $bind_data['user_id'] = $uinfo['user_id'];
                    $bind_data['access_token'] = $qc_info['access_token'];
                    $bind_data['open_id'] = $qc_info['open_id'];
                    $bind_data['nickname'] = $qc_info['nickname'];
                    $bind_data['sex'] = $qc_info['gender'];
                    $bind_data['province'] = $qc_info['province'];
                    $bind_data['city'] = $qc_info['city'];
                    $bind_data['head_img_s'] = $qc_info['head_img_s'];
                    $bind_data['head_img_b'] = $qc_info['head_img_b'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_qq_bind($bind_data);
                }elseif($utype == "sina"){//新浪
                    $this->users_model->del_weibo_bind($uinfo['user_id']);
                    $bind_data['user_id'] = $uinfo['user_id'];
                    $bind_data['access_token'] = $qc_info['access_token'];
                    $bind_data['uid'] = $qc_info['open_id'];
                    $bind_data['nickname'] = $qc_info['nickname'];
                    $bind_data['sex'] = $qc_info['gender'];
                    $bind_data['province'] = $qc_info['province'];
                    $bind_data['city'] = $qc_info['city'];
                    $bind_data['head_img_s'] = $qc_info['head_img_s'];
                    $bind_data['head_img_b'] = $qc_info['head_img_b'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_weibo_bind($bind_data);
                }elseif($utype == "weixin"){//微信
                    $this->users_model->del_weixin_bind($uinfo['user_id']);
                    $bind_data = array();
                    $bind_data['user_id'] = $uinfo['user_id'];
                    $bind_data['unionid'] = $qc_info['unionid'];
                    $bind_data['open_id'] = $qc_info['open_id'];
                    $bind_data['nickname'] = $qc_info['nickname'];
                    $bind_data['sex'] = $qc_info['sex'];
                    $bind_data['province'] = $qc_info['province'];
                    $bind_data['city'] = $qc_info['city'];
                    $bind_data['headimgurl'] = $qc_info['headimgurl'];
                    $bind_data['privilege'] = $qc_info['privilege'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_weixin_bind($bind_data);
                }
            }else{//新用户注册
                //获取新手任务配置
                $this->new_task = $this->config_task['new_task'];
                //验证密码
                if(!$upass){
                    $mess['errorMsg'] = '密码不能为空';
                    $mess['reqStatus'] = false;
                    echo JSON($mess);exit;
                }
                
                /*******************/
                //判断是否线下注册,如果是，则删除
                $line_user = $this->users_model->get_user(array("mobile"=>$umobile,"is_line"=>1));
                if($line_user){
                    $user_id = $line_user['user_id'];
                    $this->db->where(array('mobile'=>$umobile))->update("tan_users_line",array('is_reg'=>1));
                }
                /***********************/
                
                //生成salt
                $salt = random_string('alnum', 6);
                //生成加密密码
                $md5pass = md5(md5($upass) . $salt);
                //写入数据库
                $data = array();
                $data['username'] = "tll".$umobile;
                $data['password'] = $md5pass;
                $data['parent_id'] = 0;
                $data['mobile'] = $umobile;
                $data['email'] = '';
                $data['salt'] = $salt;
                $data['mobile_isApprove'] = 1;
                $data['reg_ip'] = $this->input->ip_address();
                $data['reg_time'] = time();
                $data['reg_flag'] = 2;//注册来源(1、PC，2、微信，3、Android，4、ios)
                $data['login_times'] = 1;
                $data['login_ip'] = $this->input->ip_address();
                $data['login_time'] = time();
                $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
                $data['last_ip'] = $this->input->ip_address();
                $data['last_time'] = time();
                if($user_id){
                    $data['is_line'] = 0;
                    $this->db->where("user_id",$user_id)->update("tan_users",$data);
                }else{
                    //创建用户注册信息
                    $user_id = $this->users_model->insert($data);
                }
                $month = date('Ym');
                $day = date('Ymd');
                if($user_id){
                    
                    if($utype == "qq"){//qq
                        $bind_data['user_id'] = $user_id;
                        $bind_data['access_token'] = $qc_info['access_token'];
                        $bind_data['open_id'] = $qc_info['open_id'];
                        $bind_data['nickname'] = $qc_info['nickname'];
                        $bind_data['sex'] = $qc_info['gender'];
                        $bind_data['province'] = $qc_info['province'];
                        $bind_data['city'] = $qc_info['city'];
                        $bind_data['head_img_s'] = $qc_info['head_img_s'];
                        $bind_data['head_img_b'] = $qc_info['head_img_b'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_qq_bind($bind_data);
                    }elseif($utype == "sina"){//新浪
                        $bind_data['user_id'] = $user_id;
                        $bind_data['access_token'] = $qc_info['access_token'];
                        $bind_data['uid'] = $qc_info['open_id'];
                        $bind_data['nickname'] = $qc_info['nickname'];
                        $bind_data['sex'] = $qc_info['gender'];
                        $bind_data['province'] = $qc_info['province'];
                        $bind_data['city'] = $qc_info['city'];
                        $bind_data['head_img_s'] = $qc_info['head_img_s'];
                        $bind_data['head_img_b'] = $qc_info['head_img_b'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_weibo_bind($bind_data);
                    }elseif($utype == "weixin"){//微信
                        $bind_data = array();
                        $bind_data['user_id'] = $user_id;
                        $bind_data['unionid'] = $qc_info['unionid'];
                        $bind_data['open_id'] = $qc_info['open_id'];
                        $bind_data['nickname'] = $qc_info['nickname'];
                        $bind_data['sex'] = $qc_info['sex'];
                        $bind_data['province'] = $qc_info['province'];
                        $bind_data['city'] = $qc_info['city'];
                        $bind_data['headimgurl'] = $qc_info['headimgurl'];
                        $bind_data['privilege'] = $qc_info['privilege'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_weixin_bind($bind_data);
                    }
                    
                    $task_first_finance = $this->new_task[0]['award_finance'];//首次任务注册奖励
                    $task_first_experience = $this->new_task[0]['award_experience'];//首次任务注册奖励

                    $task_second_finance = $this->new_task[1]['award_finance'];//首次绑定手机奖励
                    $task_second_experience = $this->new_task[1]['award_experience'];//首次绑定手机奖励
                    
                    //用户附加信息
                    $img_index = rand(0, 9);
                    $info_data = array();
                    $info_data['user_id'] = $user_id;
                    $info_data['truename'] = "";
                    $info_data['idcard'] = "";
                    $info_data['head_img'] = "http://static.tan66.com/upfiles/head/s/".  $img_index.".jpg";
                    $info_data['head_small_img'] = "http://static.tan66.com/upfiles/head/m/".  $img_index.".jpg";
                    $info_data['nickname'] = "tan66-".encrypt_user_id($user_id);
                    $info_data['create_time'] = time();
                    if($line_user){//下线用户更新
                        $this->db->where("user_id",$user_id)->update("tan_users_info",$info_data);
                    }else{
                        $this->users_model->insert_user_info($info_data);//插入用户附加信息
                    }
                    //用户账户信息
                    $account_data = array();
                    $account_data['user_id'] = $user_id;
                    $account_data['total'] = $task_first_finance + $task_second_finance;//账户总额
                    $account_data['balance'] = $task_first_finance + $task_second_finance;//可用余额
                    $this->account_model->insert($account_data);//插入用户账号信息

                    //新手任务
                    $new_user_task1 = array();
                    $new_user_task1['user_id'] = $user_id;
                    $new_user_task1['step'] = 1;
                    $new_user_task1['reward_worth'] = $this->new_task[0]['award_finance'];
                    $new_user_task1['reward_experience'] = $this->new_task[0]['award_experience'];
                    $new_user_task1['is_finish'] = 1;
                    $new_user_task1['is_receive'] = 1;
                    $new_user_task1['receive_time'] = time();
                    $new_user_task1['finish_time'] = time();
                    $new_user_task1['create_time'] = time();
                    $this->new_task_model->insert($new_user_task1);//新手任务第一步

                    $new_user_task2 = array();
                    $new_user_task2['user_id'] = $user_id;
                    $new_user_task2['step'] = 2;
                    $new_user_task2['reward_worth'] = $this->new_task[1]['award_finance'];
                    $new_user_task2['reward_experience'] = $this->new_task[1]['award_experience'];
                    $new_user_task2['is_finish'] = 1;
                    $new_user_task2['is_receive'] = 1;
                    $new_user_task2['receive_time'] = time();
                    $new_user_task2['finish_time'] = time();
                    $new_user_task2['create_time'] = time();
                    $this->new_task_model->insert($new_user_task2);//新手任务第二步

                    $new_user_task3 = array();
                    $new_user_task3['user_id'] = $user_id;
                    $new_user_task3['step'] = 3;
                    $new_user_task3['reward_worth'] = $this->new_task[2]['award_finance'];
                    $new_user_task3['reward_experience'] = $this->new_task[2]['award_experience'];
                    $new_user_task3['is_finish'] = 0;
                    $new_user_task3['is_receive'] = 0;
                    $new_user_task3['receive_time'] = 0;
                    $new_user_task3['finish_time'] = 0;
                    $new_user_task3['create_time'] = time();
                    $this->new_task_model->insert($new_user_task3);//新手任务第三步

                    //奖励通知
                    $message = "恭喜您完成新手任务第一步【".$this->new_task[0]['title']."】,奖励您".$this->new_task[0]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[0]['award_experience']."积分
                    $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time())); 

                    //奖励通知
                    $message = "恭喜您完成新手任务第二步【".$this->new_task[1]['title']."】,奖励您".$this->new_task[1]['award_finance']."溜溜币。感谢您对弹溜溜的支持！";//和".$this->new_task[1]['award_experience']."积分
                    $this->db->insert("users_award_notice", array('user_id'=>$user_id,'title'=>'任务通知','content'=>$message,'from'=>'弹溜溜官方','create_time'=>  time()+10)); 
                    $current_time = time();

                    if(1){
                       //资金明细
                        $finance_data = array();
                        $finance_data['user_id'] = $user_id;
                        $finance_data['content'] = '新人注册奖励礼包'.$task_first_finance.'溜溜币';
                        $finance_data['finance'] = $task_first_finance;
                        $finance_data['finance_balance'] = $account_data['balance'] - $task_first_finance;
                        $finance_data['reward_type'] = 'task_award';
                        $finance_data['type'] = 1;
                        $finance_data['create_time'] = $current_time;
                        $finance_data['month'] = $month;
                        $finance_data['day'] = $day;
                        $this->finance_list_model->insert($finance_data); 

                        $finance_data = array();
                        $finance_data['user_id'] = $user_id;
                        $finance_data['content'] = '首次绑定手机奖励'.$task_second_finance.'溜溜币';
                        $finance_data['finance'] = $task_second_finance;
                        $finance_data['finance_balance'] = $account_data['balance'];
                        $finance_data['reward_type'] = 'task_award';
                        $finance_data['type'] = 1;
                        $finance_data['create_time'] = $current_time + 10;
                        $finance_data['month'] = $month;
                        $finance_data['day'] = $day;
                        $this->finance_list_model->insert($finance_data);
                    }

                    /*********社区相关start********/
                    //创建社区用户表
                    $this->bbs_user_model->insert_bbs_user(array("user_id"=>$user_id,"salt"=>$salt,"reg_time"=>  time(),"group_id"=>1,"create_time"=>  time()));
                    //创建社区用户账户表
                    $this->bbs_user_model->insert_bbs_account(array("user_id"=>$user_id));
                    //创建社区个人统计表
                    $this->bbs_user_model->insert_bbs_count(array("user_id"=>$user_id));

                    //添加个人动态
                    //$this->insert_behavior(array('user_id'=>$this->userinfo['user_id'],"operator_id"=>0,"event_type"=>"event_reg"));
                    //系统通知
                    $this->insert_notice(array('user_id'=>0,"operator_id"=>0,"recieve_id"=>$user_id,"event_type"=>"event_reg","type"=>"system","content"=>"欢迎来到弹溜溜社区大家庭！！"));
                    /*********社区相关end********/
                    //发送欢迎私信
                    $this->send_dialog($user_id,$salt);
                    
                }
            }
            //用户日志
            $log_data = array();
            $log_data['user_id'] = $user_id;
            $log_data['events'] = 'register';
            $log_data['content'] = '注册成功';
            $log_data['ip'] = $this->input->ip_address();
            $log_data['create_time'] = time();
            $this->users_model->insert_log($log_data);

            //写入登录日志
            $login_log_data = array();
            $login_log_data['user_id'] = $user_id;
            $login_log_data['login_flag'] = 2;
            $login_log_data['login_ip'] = $this->input->ip_address();;
            $login_log_data['create_time'] = time();
            $login_log_data['month'] = date("Ym");
            $login_log_data['day'] = date("Ymd");
            $this->users_model->insert_login_log($login_log_data);

            //登录
            $info = array();
            $info['uuid'] = encrypt_user_id($user_id);
            $info['uname'] = "tll".$umobile;
            $info['mobile_flag'] = 1;
            $info['email_flag'] = 0;
            $info['last_ip'] = $data['last_ip'];
            $info['last_time'] = $data['last_time'];
            $this->session->set_userdata('userinfo', $info);
            
            $mess['reqStatus'] = true;
            $mess['url'] = site_url("account");
            echo JSON($mess);exit;
        }
    }
    
    //第三方qq登录
    function qq_login(){
        $this->load->library('Oauth');//qq第三方登录
        $qc = new QC();
        $qc->qq_login();
    }
    //第三方weibo登录
    function weibo_login(){
        $this->load->library('Weibo');//新浪微博第三方登录
        session_start();
        $wc = new SaeTOAuthV2(WB_AKEY,WB_SKEY);
        $redirect_url = $wc->getAuthorizeURL(WB_CALLBACK_URL);
        header("Location:".$redirect_url);
    }
    //第三方微信登录
    function weixin_login(){
        $this->load->library('Weixin');//微信第三方登录
        $wx = new Weixin();
        $config = array(
            "redirectUri" => site_url("account/callback_weixin_login"),
            "state" => 2
        );
        $wx->get_code($config);
    }
    //第三方qq登录回调函数
    function callback_qq_login(){
        $this->load->library('Oauth');//qq第三方登录
        $qc = new QC();
        $access_token = $qc->qq_callback();
        $open_id = $qc->get_openid();
        $where = array();
        $where['open_id'] = $open_id;
        $users_bind = $this->users_model->get_qq_bind($where);
        $ip = $this->input->ip_address();
        if($users_bind){
            $uinfo = $this->users_model->get_user_by_uid($users_bind['user_id']);
            //登录成功，写入日志记录
            $log_data = array();
            $log_data['user_id'] = $uinfo['user_id'];
            $log_data['events'] = 'login';
            $log_data['content'] = 'qq登录成功';
            $log_data['ip'] = $ip;
            $log_data['create_time'] = time();
            $this->users_model->insert_log($log_data);
            //写入登录日志
            $login_log_data = array();
            $login_log_data['user_id'] = $uinfo['user_id'];
            $login_log_data['login_flag'] = 2;
            $login_log_data['login_ip'] = $ip;
            $login_log_data['create_time'] = time();
            $login_log_data['month'] = date("Ym");
            $login_log_data['day'] = date("Ymd");
            $this->users_model->insert_login_log($login_log_data);
            
            
            //更改用户信息
            $data = array();
            $data['login_times'] = $uinfo['login_times'] + 1;
            $data['last_ip'] = $uinfo['login_ip'];
            $data['last_time'] = $uinfo['login_time'];
            $data['login_ip'] = $ip;
            $data['login_time'] = time();
            $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
            $this->users_model->user_update($data,$uinfo['user_id']);
            
            //登录
            $info = array();
            $info['uuid'] = encrypt_user_id($uinfo['user_id']);
            $info['uname'] = $uinfo['username'];
            $info['mobile_flag'] = $uinfo['mobile'] ? 1 : 0;
            $info['email_flag'] = $uinfo['email'] ? 1 : 0;
            $info['last_ip'] = $data['last_ip'];
            $info['last_time'] = $data['last_time'];
            $this->session->set_userdata('userinfo', $info);
            redirect("account");
        }else{
            $qc1 = new QC($access_token,$open_id);
            $qc_user_info = $qc1->get_user_info();
            if($qc_user_info['ret'] == 0){
                $user_info = array(
                    'access_token' => $access_token,
                    'open_id' => $open_id,
                    'nickname' => $qc_user_info['nickname'],
                    'gender' => $qc_user_info['gender'] == "男" ? "1" : '2',
                    'province' => $qc_user_info['province'],
                    'city ' => $qc_user_info['city '],
                    'head_img_s' => $qc_user_info['figureurl_qq_1'],
                    'head_img_b' => $qc_user_info['figureurl_qq_2']
                );
                //已登录用户
                if($this->userinfo){
                    $bind_data = array();
                    $bind_data['user_id'] = $this->user_id;
                    $bind_data['access_token'] = $user_info['access_token'];
                    $bind_data['open_id'] = $user_info['open_id'];
                    $bind_data['nickname'] = $user_info['nickname'];
                    $bind_data['sex'] = $user_info['gender'];
                    $bind_data['province'] = $user_info['province'];
                    $bind_data['city'] = $user_info['city'];
                    $bind_data['head_img_s'] = $user_info['head_img_s'];
                    $bind_data['head_img_b'] = $user_info['head_img_b'];
                    $bind_data['create_time'] = time();
                    $this->users_model->insert_qq_bind($bind_data);
                    $user_info_ = $this->db->query("select nickname from tan_users_info where user_id = ".$this->user_id." order by id desc limit 1")->row_array();
                    $info = array();
                    $info['nickname'] = $user_info_['nickname'] ? $user_info_['nickname'] : $user_info['nickname'];
                    $info['sex'] = $user_info['gender'];
                    $info['province'] = $user_info['province'];
                    $info['city'] = $user_info['province'];
                    $this->users_model->user_info_update($info,$this->user_id);
                    redirect('account/thirdbind');exit;//绑定成功
                }
                
                $this->assign('type','qq');
                $this->assign('head_img', $qc_user_info['figureurl_qq_2']);
                $this->assign('nickname', $qc_user_info['nickname']);
                $this->assign('qc_info', base64_encode(json_encode($user_info)));
            }else{
                $msg = $qc_user_info['msg'];
                $url = site_url('');
                echo "<script type='text/javascript'>alert('".$msg."');window.location.href='".$url."';</script>";
            }
            $this->display('site/third_bind.html');
        }
    }
    
    //第三方微博登录回调
    function callback_weibo_login(){
        $this->load->library('Weibo');//新浪微博第三方登录
        $home = site_url("");
        session_start();
        $qc = new SaeTOAuthV2(WB_AKEY,WB_SKEY);
        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = WB_CALLBACK_URL;
            try {
                    $token = $qc->getAccessToken( 'code', $keys ) ;
            } catch (OAuthException $e) {
            }
        }else{
            echo "<script type='text/javascript'>alert('访问超时，请重试！');window.location.href='".$home."';</script>";exit;
        }
        $ip = $this->input->ip_address();
        if($token){
            //判断是否已经绑定存在
            $where = array();
            $where['uid'] = $token['uid'];
            $users_bind = $this->users_model->get_weibo_bind($where);
            if($users_bind){//已绑定
                $uinfo = $this->users_model->get_user_by_uid($users_bind['user_id']);
                //登录成功，写入日志记录
                $log_data = array();
                $log_data['user_id'] = $uinfo['user_id'];
                $log_data['events'] = 'login';
                $log_data['content'] = '微博登录成功';
                $log_data['ip'] = $ip;
                $log_data['create_time'] = time();
                $this->users_model->insert_log($log_data);
                //写入登录日志
                $login_log_data = array();
                $login_log_data['user_id'] = $uinfo['user_id'];
                $login_log_data['login_flag'] = 2;
                $login_log_data['login_ip'] = $ip;
                $login_log_data['create_time'] = time();
                $login_log_data['month'] = date("Ym");
                $login_log_data['day'] = date("Ymd");
                $this->users_model->insert_login_log($login_log_data);


                //更改用户信息
                $data = array();
                $data['login_times'] = $uinfo['login_times'] + 1;
                $data['last_ip'] = $uinfo['login_ip'];
                $data['last_time'] = $uinfo['login_time'];
                $data['login_ip'] = $ip;
                $data['login_time'] = time();
                $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
                $this->users_model->user_update($data,$uinfo['user_id']);

                //登录
                $info = array();
                $info['uuid'] = encrypt_user_id($uinfo['user_id']);
                $info['uname'] = $uinfo['username'];
                $info['mobile_flag'] = $uinfo['mobile'] ? 1 : 0;
                $info['email_flag'] = $uinfo['email'] ? 1 : 0;
                $info['last_ip'] = $data['last_ip'];
                $info['last_time'] = $data['last_time'];
                $this->session->set_userdata('userinfo', $info);
                redirect("account");
            }else{
                $qc = new SaeTClientV2(WB_AKEY,WB_SKEY,$token['access_token']);
                $uid_get = $qc->get_uid();
                $uid = $uid_get['uid'];
                $qc_user_info = $qc->show_user_by_id( $uid);//根据ID获取用户等基本信息
                if(!$qc_user_info['error_code']){
                    $locat_arr = explode(" ", $qc_user_info['location']);
                    $user_info = array(
                        'access_token' => $token['access_token'],
                        'open_id' => $token['uid'],
                        'nickname' => $qc_user_info['screen_name'],
                        'gender' => $qc_user_info['gender'] == "f" ? "2" : '2',
                        'province' => $locat_arr[0],
                        'city ' => $locat_arr[1],
                        'head_img_s' => $qc_user_info['profile_image_url'],
                        'head_img_b' => $qc_user_info['avatar_hd']
                    );
                    //已登录用户
                    if($this->userinfo){
                        $bind_data = array();
                        $bind_data['user_id'] = $this->user_id;
                        $bind_data['access_token'] = $user_info['access_token'];
                        $bind_data['uid'] = $user_info['open_id'];
                        $bind_data['nickname'] = $user_info['nickname'];
                        $bind_data['sex'] = $user_info['gender'];
                        $bind_data['province'] = $user_info['province'];
                        $bind_data['city'] = $user_info['city'];
                        $bind_data['head_img_s'] = $user_info['head_img_s'];
                        $bind_data['head_img_b'] = $user_info['head_img_b'];
                        $bind_data['create_time'] = time();
                        $this->users_model->insert_weibo_bind($bind_data);
                        
                        $user_info_ = $this->db->query("select nickname from tan_users_info where user_id = ".$this->user_id." order by id desc limit 1")->row_array();
                        $info = array();
                        $info['nickname'] = $user_info_['nickname'] ? $user_info_['nickname'] : $user_info['nickname'];
                        $info['sex'] = $user_info['gender'];
                        $info['province'] = $user_info['province'];
                        $info['city'] = $user_info['province'];
                        $this->users_model->user_info_update($info,$this->user_id);
                        redirect('account/thirdbind');exit;//绑定成功
                    }
                    $this->assign('type',"sina");
                    $this->assign('head_img', $qc_user_info['avatar_hd']);
                    $this->assign('nickname', $qc_user_info['screen_name']);
                    $this->assign('qc_info', base64_encode(json_encode($user_info)));
                }else{
                    $msg = $qc_user_info['error'];
                    $url = site_url('');
                    echo "<script type='text/javascript'>alert('".$msg."');window.location.href='".$url."';</script>";
                }
                $this->display('site/third_bind.html');
            }
        }
    }
    
    //第三方微信登录
    function callback_weixin_login(){
        if($_REQUEST){
            $code = trim($_REQUEST['code']);
            if(!$code){
                echo "非法请求";die;
            }
            $this->load->library('Weixin');//微信第三方登录
            $wx = new Weixin();
            $token = $wx->get_access_token($code);
            $token = json_decode($token, true);
            if($token['errcode']){
                echo "授权失败，原因：".$token['errmsg'];die;
            }
            
            $ip = $this->input->ip_address();
            //判断是否已经绑定存在
            $where = array();
            $where['unionid'] = $token['unionid'];
            $users_bind = $this->users_model->get_weixin_bind($where);
            if($users_bind){//已绑定
                $uinfo = $this->users_model->get_user_by_uid($users_bind['user_id']);
                //登录成功，写入日志记录
                $log_data = array();
                $log_data['user_id'] = $uinfo['user_id'];
                $log_data['events'] = 'login';
                $log_data['content'] = '微信登录成功';
                $log_data['ip'] = $ip;
                $log_data['create_time'] = time();
                $this->users_model->insert_log($log_data);
                //写入登录日志
                $login_log_data = array();
                $login_log_data['user_id'] = $uinfo['user_id'];
                $login_log_data['login_flag'] = 2;
                $login_log_data['login_ip'] = $ip;
                $login_log_data['create_time'] = time();
                $login_log_data['month'] = date("Ym");
                $login_log_data['day'] = date("Ymd");
                $this->users_model->insert_login_log($login_log_data);


                //更改用户信息
                $data = array();
                $data['login_times'] = $uinfo['login_times'] + 1;
                $data['last_ip'] = $uinfo['login_ip'];
                $data['last_time'] = $uinfo['login_time'];
                $data['login_ip'] = $ip;
                $data['login_time'] = time();
                $data['login_flag'] = 2;//登录来源(1、PC，2、微信，3、Android，4、ios)
                $this->users_model->user_update($data,$uinfo['user_id']);

                //登录
                $info = array();
                $info['uuid'] = encrypt_user_id($uinfo['user_id']);
                $info['uname'] = $uinfo['username'];
                $info['mobile_flag'] = $uinfo['mobile'] ? 1 : 0;
                $info['email_flag'] = $uinfo['email'] ? 1 : 0;
                $info['last_ip'] = $data['last_ip'];
                $info['last_time'] = $data['last_time'];
                $this->session->set_userdata('userinfo', $info);
                redirect("account");
            }else{
                $userinfo = $wx->get_userinfo($token['access_token'], $token['openid']);
                $userinfo = json_decode($userinfo, true);
                
                if(!$userinfo['errcode']){
                    $user_info = array(
                        'unionid' => $userinfo['unionid'],
                        'open_id' => $userinfo['headimgurl'],
                        'nickname' => $userinfo['nickname'],
                        'sex' => $userinfo['sex'],
                        'province' => $userinfo["province"],
                        'city ' => $userinfo["city"],
                        'headimgurl' => $userinfo['headimgurl'],
                        'privilege' => serialize($userinfo['privilege']),
                    );
                    
                    //已登录用户
                    if($this->userinfo){
                        $bind_data = array();
                        $bind_data['user_id'] = $this->user_id;
                        $bind_data['unionid'] = $user_info['unionid'];
                        $bind_data['open_id'] = $user_info['open_id'];
                        $bind_data['nickname'] = $user_info['nickname'];
                        $bind_data['sex'] = $user_info['sex'];
                        $bind_data['province'] = $user_info['province'];
                        $bind_data['city'] = $user_info['city'];
                        $bind_data['headimgurl'] = $user_info['headimgurl'];
                        $bind_data['privilege'] = $user_info['privilege'];
                        $bind_data['create_time'] = time();
                        
                        $this->users_model->insert_weixin_bind($bind_data);
                        $user_info_ = $this->db->query("select nickname from tan_users_info where user_id = ".$this->user_id." order by id desc limit 1")->row_array();
                        $info = array();
                        $info['nickname'] = $user_info_['nickname'] ? $user_info_['nickname'] : $user_info['nickname'];
                        $info['sex'] = $user_info['sex'];
                        $info['province'] = $user_info['province'];
                        $info['city'] = $user_info['city'];
                        $this->users_model->user_info_update($info,$this->userinfo['user_id']);
                        redirect('account/thirdbind');exit;//绑定成功
                    }
                    $this->assign('type',"weixin");
                    $this->assign('head_img', $user_info['headimgurl']);
                    $this->assign('nickname', $user_info['nickname']);
                    $this->assign('qc_info', base64_encode(json_encode($user_info)));
                }else{
                    $msg = $userinfo['errmsg'];
                    $url = site_url('');
                    echo "<script type='text/javascript'>alert('".$msg."');window.location.href='".$url."';</script>";
                }
                $this->display('site/third_bind.html');
            }
        }
    }
    
    //退出登录
    function logout(){
        $this->session->sess_destroy();
        echo '<script type="text/javascript">window.location.href="' .site_url("account") .
        '"</script>';
    }
    
    //欢迎私信的发送
    private function send_dialog($userid,$room_name){
        $this->load->model('bbs_dialog_model');
        
        $room_name = random_string('alnum', 6);
        
        $dialog_room = array(
            0=>array("room_name"=>$room_name,"dialog_from"=>13010,"dialog_to"=>$userid,"is_del"=>0,"is_show"=>0),
            1=>array("room_name"=>$room_name,"dialog_from"=>$userid,"dialog_to"=>13010,"is_del"=>0,"is_show"=>0)
        );
        $this->bbs_dialog_model->insert_dialog_room($dialog_room);
        $current_time = time();
        $data = array();
        $data['room_name'] = $room_name;
        $data['sender_from_id'] = 13010;
        $data['sender_to_id'] = $userid;
        $data['create_time'] = $current_time;
        $data['content'] = "Hello！ 我是弹溜溜小秘书 :) 欢迎您的到来，成为万千弹溜溜小伙伴中的一员。弹溜溜是个多元化的科技金融互动社群，在这里不仅可以参与最前沿的互联网金融体验，还可以发现更多志趣相投的伙伴、分享你的理财经验、交流投资心得等，更有可爱的客服妹纸随时为您排忧解难。对了，顺便问下，您是怎么知道弹溜溜的？";
        $data['is_read'] = 0;
        $data['is_show'] = 0;
        $this->bbs_dialog_model->insert_message($data);
    }
    //判断是否登录
    //是否登录
    private function is_login(){
        if(!$this->user_id){redirect("account/login");exit;}
    }
}
